﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using SimpleServiceBus.Utilities;

namespace SimpleServiceBus.Persistence.NHibernate
{
    public class DataSessionUnitOfWork : IDisposable
    {
        private ISessionManager _sessionManager;
        private bool _isSessionOwner = false;

        public DataSessionUnitOfWork():this(null)
        {
        }

        public DataSessionUnitOfWork(ISessionManager sessionManager)
        {
            _sessionManager = sessionManager ?? DataSessionManager.Current;
            if (_sessionManager.CurrentSession == null)
            {
                _isSessionOwner = true;
                Begin();
            }
        }

        public void Dispose()
        {
            if (_isSessionOwner)
                Complete();
        }

        public ISessionManager SessionManager
        {
            get { return _sessionManager;}
        }

        private void Begin()
        {
            if (_sessionManager == null)
                throw new InvalidOperationException(
                    "There is no SessionManager configured to service this unit of work.");
            _sessionManager.BeginSession();
        }

        private void Complete()
        {
           if (_sessionManager != null)
               _sessionManager.EndSession();
            _sessionManager = null;
        }

        
    }
}
